package poker.plans.croupier;

import java.util.*;

import jadex.adapter.fipa.*;
import jadex.runtime.*;

import poker.beliefs.*;
import poker.util.HandChecker;


public class DetermineHandWinnerPlan extends Plan {

	public void body() {
		//Hashtable to store the hands of each player
		System.out.println("CROUPIER: Time to determine this hand winner");
		Vector<AgentIdentifier> showAgents = new Vector<AgentIdentifier>();
		Vector<Hand> showHands = new Vector<Hand>();
		
		//Get the players that are active in this hand
		List gamers = (List)getBeliefbase().getBelief("gamers").getFact();
		
		//Send a showHand message to each player
		IMessageEvent msg,answer;
		Hand playerHand;
		AgentIdentifier id;
		Iterator it = gamers.iterator();
		while(it.hasNext()) {
			id = (AgentIdentifier) it.next();
			msg = createMessageEvent("showHand");
			msg.getParameterSet(SFipa.RECEIVERS).addValue(id);
			System.out.println("CROUPIER: Asking player "+id.getName()+" his hand");
			answer = sendMessageAndWait(msg);
			//Here we can do some checking in the answer of the player
			playerHand = (Hand) answer.getContent();
			showAgents.add(id);
			showHands.add(playerHand);
		}
		
		//Now let's determine the winning hand
		Vector<AgentIdentifier> winAgents = new Vector<AgentIdentifier>();
		winAgents.add(showAgents.firstElement());
		Hand winHand = showHands.firstElement();
		int winRank = HandChecker.rankHand(winHand);
		int auxRank;
		for (int i = 1; i < showHands.size(); i++) {
			auxRank = HandChecker.rankHand(showHands.get(i));
			if (auxRank > winRank) {
				//We have found a player with a better Hand
				//So we clean the winAgents vector to delete the no-longer-winnners
				winAgents.clear();
				//and we add the new one
				winAgents.add(showAgents.get(i));
				winRank = auxRank;
				winHand = showHands.get(i);
			}
			else if (auxRank == winRank) {
				//We have found a player with a equivalent hand: we have a tie
				winAgents.add(showAgents.get(i));
			}
		}
		it = winAgents.iterator();
		int totalpot = ((Integer)getBeliefbase().getBelief("acpot").getFact()).intValue();
		IMessageEvent youwin = createMessageEvent("youWin");
		youwin.setContent(new Integer(totalpot/winAgents.size()));
		while (it.hasNext()) {
			id = (AgentIdentifier) it.next();
			System.out.println("CROUPIER: "+id.getName()+" is a winner with hand "+winRank);
			youwin.getParameterSet(SFipa.RECEIVERS).addValue(id);
		}
		sendMessage(youwin);
		
		// Now we have to tell the others the result of the game
		GameResult grs = new GameResult();
		grs.setWinners(winAgents);
		grs.setWinnerHand(winHand);
		IGoal notifyResult = createGoal("notify_result");
		notifyResult.getParameter("game_result").setValue(grs);
        dispatchSubgoalAndWait(notifyResult);
        
        /*
        IGoal deal = createGoal("deal_cards");
        dispatchTopLevelGoal(deal);
        */
	}
	
}
